;;; Script servidor.
(ns appli.server
(:gen-class)
(:use clojure.contrib.duck-streams read.readDB)
)
(import '(java.net Socket ServerSocket)
        '(java.io PrintWriter OutputStream DataOutputStream DataInputStream BufferedReader))

(def *port* 3003)


(defn write
  "Writes in server DB. Receives one parameter: the socket of the Client."	
  [_ socketClient]
  (loop []
		  (let [
				input		(DataInputStream. (.getInputStream socketClient))
				output		(DataOutputStream. (.getOutputStream socketClient))
				db        	(atom "db-1x2.db")
				elementsArr	(.split (.readUTF input) "#")
				get-pos		(aget elementsArr 0)
				name		(aget elementsArr 1)
				location 	(aget elementsArr 2)
				size     	(aget elementsArr 3)
				smoking  	(aget elementsArr 4)
				rate     	(aget elementsArr 5)
				date     	(aget elementsArr 6)
				owner    	(aget elementsArr 7)
				agent		(agent nil)
			]
			(write-row-with-values @db (Integer. get-pos) name location size smoking rate date owner)
			(println (str "Received to write from: " (.getRemoteSocketAddress socketClient)))
			(println get-pos)
			(println name)
			(println location)
			(println size)
			(println smoking)
			(println rate)
			(println date)
			(println owner)
		  )
		(recur)
	)
)

(defn serverLoop
	"Waits to receive new conections"
	[]
	(let 
		[server    (ServerSocket. *port*)]
		(loop []
			(println "wating request...")
			(let [
					socketClient (.accept server)
					output 		(DataOutputStream. (.getOutputStream socketClient))
					agent		(agent nil)
				]
				(println (str "Client " (.getRemoteSocketAddress socketClient) " connected."))
				(.writeUTF output (str (System/getProperty "user.dir")))
				
				(clear-agent-errors agent)
				(send agent write socketClient)
			)
			(recur)
		)
	)
)